<template>
  <div class="main" :style="mainStyle">
    <!-- 饼图 -->
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div :id="props.id" class="bar" :style="echartsStyle"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";

let props = defineProps([
  "id",
  "xAxisData",
  "xAxisParams",
  "seriesData",
  "size",
  "titleText",
  "yAxisParams",
]);
const emit = defineEmits(["fatherMethods"]);
const { proxy } = getCurrentInstance();

let echartsStyle = computed(() => {
  if (props.size) return { height: `${props.size}px`, width: "100%" };
  return {
    position: "absolute",
    top: 0,
    left: 0,
    width: "100%",
    height: "100%",
  };
});

let mainStyle = computed(() => {
  if (props.size) return;
  return {
    width: "100%",
    height: 0,
    "padding-top": "100%",
    position: "relative",
  };
});

let colors = computed(() => {
  let arr = ["#5470c6", "#3ba272", "#ee6666", "#fac858", "#73c0de", "#3ba272"];
  //return proxy.$utils.shuffle(arr);
  return arr;
});

let init = () => {
  let myChart = echarts.init(document.getElementById(props.id));
  myChart.clear(); // 适用于大数据量的切换时图表绘制错误,先清空在重绘

  //点击选中
  myChart.on("click", function (e) {
    emit("fatherMethods", e);
  });
  let option = {
    tooltip: {
      //滑动到柱状图上
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      orient: "horizontal",
      left: "left",
    },
    title: {
      text: props.titleText,
      left: "center",
    },
    xAxis: {
      type: "category",
      data: props.xAxisData,
      axisLabel: {
        formatter: function (value) {
          return value.length > 20 ? value.slice(0, 20) + "..." : value;
        },
      },
    },
    yAxis: {
      type: "value",
    },
    series: props.seriesData,
  };
  if (props.yAxisParams) option.yAxis = props.yAxisParams;
  if (props.xAxisParams) option.xAxis = props.xAxisParams;
  myChart.setOption(option);
};

watch(
  () => props.seriesData,
  (newValue, oldValue) => {
    if (newValue && newValue.length) {
      nextTick(() => {
        init();
      });
    }
  },
  { immediate: true, deep: true }
);
</script>



<style lang="scss" scoped>
</style>
